<?php


namespace app\user\controller;


use app\common\controller\Api;
use app\user\model\AddressModel;
use app\user\validate\AddressValidate;
use function fast\e;

class Address extends Base
{
    protected $noNeedLogin = '*';

    public function index()
    {
        $user_id = input('user_id/d');
        if (empty($user_id)) {
            $this->error('id不能为空');
        }
        $address = AddressModel::order('id','DESC')
            ->where('user_id',$user_id)
            ->field('id,name,mobile,area,address')
            ->select();
        if (!$address){
            $this->error('该用户下没有地址');
        }
        $this->success('查询成功',[
            'address' => $address
        ]);
    }

    public function add()
    {
        $date = input('post.');
        //验证数据
        $validate = new AddressValidate();
        $result = $validate->scene('add')->check($date);
        if (!$result) {
            $this->error($validate->getError());
        }
        $address = AddressModel::where('address',$date['address'])->find();
        if ($address){
            $this->error('该地址已经存在');
        }
        $date['create_time'] = date('Y-m-d H:i:s');
        if (AddressModel::create($date)){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    public function edit()
    {
        $id = input('id/d');
        if (empty($id)){
            $this->error('id不能为空');
        }
        $address = AddressModel::field('id,name,mobile,area,address')->find($id);
        if (!$address){
            $this->error('查询失败');
        }
        $this->success('查询成功',[
            'address' => $address
        ]);
    }

    public function update()
    {
        $date = input('post.');
        $validate = new AddressValidate();
        $result = $validate->scene('edit')->check($date);
        if (!$result) {
            $this->error($validate->getError());
        }
        $user = AddressModel::where('id',$date['id'])->find();
        if(!$user){
            return error('该地址未拥有');
        }
        $user->mobile = $date['mobile'];
        $user->area = $date['area'];
        $user->name = $date['name'];
        $user->address = $date['address'];
        if ($user->save()) {
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }

    public function delete()
    {
        $id = input('id/d');
        if (empty($id)) {
            $this->error('id不能为空');
        }
        $news = AddressModel::find($id);
        if (!$news) {
            $this->error('地址不存在');
        }

        if ($news->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


}